package com.example.elderlycare.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.elderlycare.controller.entity.OutRecordRequestBody;
import com.example.elderlycare.dao.entity.CheckRecord;
import com.example.elderlycare.dao.entity.OutRecord;
import com.example.elderlycare.service.CheckRecordService;
import com.example.elderlycare.service.OutRecordService;
import com.example.elderlycare.service.entity.OutRecordResponseBody;
import com.example.elderlycare.utils.Result;
import com.example.elderlycare.utils.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/out_record")
public class OutRecordController {

    @Resource
    OutRecordService outRecordService;

    @Resource
    CheckRecordService checkRecordService;

    /**
     * 查询外出登记记录
     *
     * @param elderName  老人姓名
     * @param escortName 陪同人姓名
     * @param isReturn   是否返回，0--未返回，1--已返回
     * @param startDate  根据日期范围查询的开始日期
     * @param endDate    根据日期范围查询的结束日期
     * @param pageSize   页大小
     * @param current    当前页
     * @return OutRecordResponseBody
     */
    @GetMapping("/query")
    public Result<OutRecordResponseBody> queryOutRecords(
            @RequestParam(value = "elderName", required = false) String elderName,
            @RequestParam(value = "escortName", required = false) String escortName,
            @RequestParam(value = "isReturn", required = false) Integer isReturn,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(defaultValue = "10", value = "pageSize") int pageSize,
            @RequestParam(defaultValue = "1", value = "current") int current) {
        Map<String, Object> params = new HashMap<>(10);
        params.put("limit", pageSize);
        params.put("offset", (current - 1) * pageSize);
        params.put("elderName", elderName != null ? "%" + elderName + "%" : null);
        params.put("escortName", escortName != null ? "%" + escortName + "%" : null);
        params.put("isReturn", isReturn);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        try {
            OutRecordResponseBody res = outRecordService.queryOutRecords(params);
            return Result.success(res);
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }

    /**
     * 新增外出登记记录
     *
     * @param req OutRecordRequestBody.addOutRecord
     * @return null
     */
    @PostMapping("/add")
    public Result<?> addOutRecord(@RequestBody OutRecordRequestBody.addOutRecord req) {
        /* 获取入住登记记录 */
        Integer checkRecordId = req.getCheckRecordId();
        CheckRecord checkRecord = checkRecordService.getById(checkRecordId);

        OutRecord outRecord = OutRecord.builder()
                .escortName(req.getEscortName())
                .escortPhone(req.getEscortPhone())
                .elderId(checkRecord.getElderId())
                .outDate(req.getOutDate())
                .planReturnDate(req.getPlanReturnDate())
                .isRefund(req.getIsRefund())
                .reason(req.getReason())
                .transactor(req.getTransactor())
                .build();
        try {
            boolean flag = outRecordService.save(outRecord);
            if (flag) {
                /* 入住状态: 111-已入住 112-已退住 113-已外出 */
                /* 入住登记记录中的入住状态更新为已外出 */
                checkRecord.setInStatusId(113);
                checkRecordService.updateById(checkRecord);
                return Result.success(null);
            } else {
                log.warn("add outRecord error");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }

    }

    /**
     * 删除外出登记记录
     *
     * @param id 记录id
     * @return null
     */
    @DeleteMapping("/delete")
    public Result<?> deleteOutRecord(@RequestParam("id") @NotEmpty Integer id) {
        try {
            boolean flag = outRecordService.removeById(id);
            if (flag) {
                return Result.success(null);
            } else {
                log.warn("delete outRecord error");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }

    }

    /**
     * 修改外出登记记录
     *
     * @param req OutRecordRequestBody.updateOutRecord
     * @return null
     */
    @PutMapping("/update")
    public Result<?> updateOutRecord(@RequestBody OutRecordRequestBody.updateOutRecord req) {
        OutRecord outRecord = OutRecord.builder()
                .id(req.getId())
                .escortName(req.getEscortName())
                .escortPhone(req.getEscortPhone())
                .isRefund(req.getIsRefund())
                .reason(req.getReason())
                .realReturnDate(req.getRealReturnDate())
                .refundDate(req.getRefundDate())
                .transactor(req.getTransactor())
                .build();
        try {
            boolean flag = outRecordService.updateById(outRecord);
            if (flag) {
                /* 获取外出登记记录 */
                outRecord = outRecordService.getById(req.getId());
                /* 如果已经返回，需要将老人入住登记的入住状态从 已外出 更新为 已入住 */
                if (outRecord.getRealReturnDate() != null) {
                    /* 入住状态: 111-已入住 112-已退住 113-已外出 */
                    UpdateWrapper<CheckRecord> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("elder_id", outRecord.getElderId())
                            .eq("in_status_id", 113)
                            .set("in_status_id", 111);
                    checkRecordService.update(updateWrapper);
                }
                return Result.success(null);
            } else {
                log.warn("update outRecord error");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }

    }
}
